//
//  MusicDetailViewController.m
//  哎游
//
//  Created by 康守帅 on 14-12-31.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "MusicDetailViewController.h"
#import "macro.h"
#import "MusicDetailTableViewCell.h"
#import "MusicDetailModel.h"
#import "AFJSONRequestOperation.h"
#import "MusicModel.h"
#import "UIImageView+WebCache.h"
#import "MusicView.h"
#import "MusicPlayerViewController.h"
#import "Singleton.h"

@interface MusicDetailViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@end

@implementation MusicDetailViewController

- (void)dealloc
{
    [_ID release];
    [_tableArray release];
    [_tableView release];
    [_imageUrl release];
    [_musicUrlArray release];
    [_index release];
    [_timer release];
    [super dealloc];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.tableArray = [NSMutableArray array];
        self.musicUrlArray = [NSMutableArray array];

    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button setBackgroundImage:[UIImage imageNamed:@"return.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(returnBack) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 50, 45)];
    label.textColor = [UIColor whiteColor];
    label.text = @"音乐列表";
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:20];
    self.navigationItem.titleView = label;
    
    [label release];
    [button release];

    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 30, self.view.frame.size.height / 2 - 90, 60, 60)];
    _imageView.image = [UIImage imageNamed:@"fireLogin.png"];
    _imageView.layer.cornerRadius = 30;
    _imageView.clipsToBounds = YES;
    [self.view addSubview:_imageView];
    
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    rotationAnimation.duration = 2;
    rotationAnimation.RepeatCount = 10000;
    rotationAnimation.cumulative = NO;
    rotationAnimation.removedOnCompletion = NO;
    rotationAnimation.fillMode = kCAFillModeBoth;
    [_imageView.layer addAnimation:rotationAnimation forKey:@"rotation"];
    
    [self startJson];
}

- (void)createLeftButton
{
    
}

- (void)viewDidAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)startJson
{
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/1/30?device=iPhone", self.ID];
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        [_imageView removeFromSuperview];
        MusicDetailModel *model = [[MusicDetailModel alloc] init];
        [model setValuesForKeysWithDictionary:JSON];
        self.imageUrl = [model.album objectForKey:@"coverOrigin"];
        
        [self.musicUrlArray removeAllObjects];
        [self.tableArray removeAllObjects];
        for (NSDictionary *dic1 in [model.tracks objectForKey:@"list"]) {
            MusicModel *music = [[MusicModel alloc] init];
            [music setValuesForKeysWithDictionary:dic1];
            music.imageUrl = self.imageUrl;
            [self.musicUrlArray addObject:music.playUrl64];
            [self.tableArray addObject:music];
            [music release];
        }
        [model release];
//        [_tableView reloadData];
        [self createView];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"发生错误%@", error);
    }];
    [operation start];
}

- (void)createView
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width)];
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageUrl] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    imageView.contentMode = UIViewContentModeScaleToFill;
    if ([_tableArray count] < 7) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 6 * 60 + 100) style:UITableViewStylePlain];
    }else {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, [_tableArray count] * 60 + 100) style:UITableViewStylePlain];
    }
    _tableView.delegate = self;
    _tableView.dataSource = self;

    [_tableView registerClass:[MusicDetailTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self createHeaderView];
    _tableView.backgroundColor = [UIColor clearColor];
    MusicView *musicView = [[MusicView alloc] initWithBackGroundView:imageView foreGroundView:_tableView];
    musicView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    musicView.backGroundHeight = 200.0f;
    musicView.delegate = self;
    [self.view addSubview:musicView];
}

- (void)createHeaderView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];
    view.backgroundColor = [UIColor clearColor];
    
    UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];
    maskView.backgroundColor = [UIColor blackColor];
    [view addSubview:maskView];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 60, 40, 50, 50)];
    [button setBackgroundImage:[UIImage imageNamed:@"play1.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, self.view.frame.size.width - 60, 30)];
    title.font = [UIFont systemFontOfSize:20];
    title.backgroundColor = [UIColor clearColor];
    title.text = self.name;
    title.textColor = [UIColor whiteColor];
    [view addSubview:title];
    
    maskView.alpha = 0.05;
    self.tableView.tableHeaderView = view;
    [view release];
}

- (void)buttonAction:(id)sender
{
    NSLog(@"sd");
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_tableArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    MusicModel *model = [_tableArray objectAtIndex:indexPath.row];
    cell.title.text = model.title;
    cell.author.text = model.nickname;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.index = indexPath;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(cancelSelectCellState) userInfo:nil repeats:NO];
    
    Singleton *share = [Singleton shareInstance];
    MusicModel *model = [_tableArray objectAtIndex:indexPath.row];
    share.musicPlayerViewController.musicArray = self.tableArray;
    if ([share.musicId isEqualToString:[model.trackId stringValue]]) {
        share.musicPlayerViewController.sameMusic = YES;
    }else {
        share.musicPlayerViewController.sameMusic = NO;
        share.musicId = [model.trackId stringValue];
        share.musicPlayerViewController.imageUrl = self.imageUrl;
        share.musicPlayerViewController.buttonState = PlayButton;
    }
    [self presentViewController:share.musicPlayerViewController animated:YES completion:nil];
}

- (void)myLogin:(id)sender
{
    
}
- (void)cancelSelectCellState
{
    [self.tableView deselectRowAtIndexPath:self.index animated:NO];
    [self.timer invalidate];
}

- (void) returnBack
{
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
